package com.ldn.starter.config;

import cn.dev33.satoken.interceptor.SaInterceptor;
import jakarta.validation.constraints.NotNull;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.PathMatchConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import com.ldn.controller.annotation.LdnManageController;
import com.ldn.controller.annotation.LdnMiniProgramController;
import com.ldn.starter.interceptor.RequestInterceptorImpl;

/**
 * @author 李大牛家的牛 (scafel@163.com)
 * @createDate 2024/7/9 - 17:06
 * @description 复写部分webmvc配置
 **/
@Configuration
public class MyMVCConfig implements WebMvcConfigurer {

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new RequestInterceptorImpl());
        // 注册 Sa-Token 拦截器，打开注解式鉴权功能
        registry.addInterceptor(new SaInterceptor()).addPathPatterns("/**");
        WebMvcConfigurer.super.addInterceptors(registry);
    }

    @Override
    public void configurePathMatch(@NotNull PathMatchConfigurer configurer) {
        // 用于处理请求接口前缀
        configurer.addPathPrefix("api/manage", c -> c.isAnnotationPresent(LdnManageController.class));
        configurer.addPathPrefix("api/mp", c -> c.isAnnotationPresent(LdnMiniProgramController.class));
        WebMvcConfigurer.super.configurePathMatch(configurer);
    }

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        // 用于解决跨域问题
        registry.addMapping("/**")
                // 发送cookie
                .allowCredentials(true)
                //设置放行哪些原始域
                .allowedOriginPatterns(
                        "http://127.0.0.1:5173",
                        "http://127.0.0.1:5172",
                        "http://127.0.0.1:5171",
                        "http://127.0.0.1"
                )
                //允许访问的域
                .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS", "PATCH")
                //允许携带请求头的域
                .allowedHeaders("*")
                //允许携带请求参数的域
                .exposedHeaders("*")
                .maxAge(36000);
        WebMvcConfigurer.super.addCorsMappings(registry);
    }

}
